<template>
  <div class="body">
    <!-- 自定义导航按钮 -->
    <div class="page_navigate">
      <div id="page_creator" class="selected" @click="toPage('creator')">生成PPT</div>
      <div id="page_dashboard" @click="toPage('dashboard')">PPT列表</div>
      <div id="page_customTemplate" @click="toPage('customTemplate')">自定义模板</div>
      <div @click="Teacher()">TeacherPPT教程</div>
    </div>
    <!-- 挂载iframe容器 -->
    <div id="container"></div>
  </div>
</template>

<script>
import "~/js/docmee-ui-sdk-iframe.min.js";
import {useUserStore} from "~/stores/user";
import {LoginPopupTypeEnum} from "~/enums/appEnums";
import {ElMessageBox} from 'element-plus'
import {pptUse} from "~/api/user";

export default {
  name: 'AiPPT',
  data() {
    return {
      docmeeUI:'',
      limit: null,
      uid: 95716789,
      currentPage: 'dashboard', // 默认页面
      apiKey: 'ak_uKiSyl356rF5TvETeu', // 替换为你的API密钥
      token: '' // 将在这里动态创建token
    };
  },
  methods: {
    Teacher(){
      window.location.href = 'https://mp.weixin.qq.com/s/Oj8bupeGNF4fEb3IQNgOAw'
    },
    async isMoney(num = 100) {
      const userStore = useUserStore()
      const router = useRouter()
      if(userStore.userInfo.balance < num || !userStore.userInfo.balance){
        await ElMessageBox.confirm(
            'T币不足，请获取足够T币后继续使用',
            '提示',
            {
              confirmButtonText: '获取T币',
              cancelButtonText: '暂不使用',
              type: 'warning',
            }
        ).then(() => {
              router.push('/openvip?mode=recharge');
            })
            .catch(() => {

            })
        return false;
      }else{
        return true;
      }
    },
    async isTbi() {
      try {
        await ElMessageBox.confirm(
            '智能创作PPT需要消耗100T币',
            '提示',
            {
              showClose: false,
              confirmButtonText: '继续',
              cancelButtonText: '关闭'
            });

        return true;
      } catch (e) {
        return false;
      }
    },
    async isTbiMb() {
      try {
        await ElMessageBox.confirm(
            '智能解析完整模板需要消耗200T币',
            '提示',
            {
              showClose: false,
              confirmButtonText: '继续',
              cancelButtonText: '关闭'
            });

        return true;
      } catch (e) {
        return false;
      }
    },
    pptUsePost(price = 100) {
      return pptUse({
        model_id: 1,
        answer_id: 2,
        deduct: price
      }).then((res) => {
        return true; // 明确返回操作成功标识‌:ml-citation{ref="1,4" data="citationList"}
      }).catch((error) => {
       // ElMessage.error(error); // 可选：显示错误提示‌:ml-citation{ref="4" data="citationList"}
        return new Promise((resolve, reject) => {
          ElMessageBox.confirm(
              error,
              '提示',
              {
                confirmButtonText: '去充值',
                cancelButtonText: '暂不使用',
                type: 'warning',
              }
          ).then(() => {
            const router = useRouter()
            router.push('/openvip?mode=recharge');
            resolve(false); // 返回充值操作状态‌:ml-citation{ref="3,4" data="citationList"}
          }).catch(() => {
            resolve(false); // 返回取消操作状态‌:ml-citation{ref="3,4" data="citationList"}
          });
        });
      });
    }
    ,
    // 创建token
    async createApiToken() {
      let that = this
      if (!this.apiKey) {
        return feedback.msgError('请在代码中设置apiKey：' + resp.message)
      }
      const url = 'https://docmee.cn/api/user/createApiToken'
      const resp = await (await fetch(url, {
        method: 'POST',
        headers: {
          'Api-Key': this.apiKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          uid: this.uid,
          limit: null
        })
      })).json()
      if (resp.code != 0) {
        return feedback.msgError('创建接口token异常：' + resp.message)
      }
      this.token = resp.data.token
      // 初始化 UI iframe
      const docmeeUI = new DocmeeUI({
        pptId: null,
        token: this.token, // token
        container: document.querySelector('#container'), // 挂载 iframe 的容器
        page: 'creator', // 'dashboard' ppt列表; 'creator' 创建页面; 'customTemplate' 自定义模版; 'editor' 编辑页（需要传pptId字段）
        lang: 'zh', // 国际化
        mode: 'light', // light 亮色模式, dark 暗色模式
        isMobile: false, // 移动端模式
        hidePdfWatermark:true,// 隐藏水印
        background: 'linear-gradient(-157deg,#f57bb0, #867dea)', // 自定义背景
        padding: '40px 20px 0px',
        onMessage(message) {
          console.log(message)
          if (message.type === 'invalid-token') {
            // 在token失效时触发
            console.log('token 认证错误')
            // 更换新的 token
            let newToken = this.createApiToken(this.apiKey, this.uid, this.limit)
            that.docmeeUI.updateToken(newToken)
          } else if (message.type === 'beforeGenerate') {
            const {subtype, fields} = message.data
            if (subtype === 'outline') {
              that.docmeeUI.sendMessage({
                type: 'success',
                content: '稍等，正在生成PPT...'
              });
              return true;
            } else if (subtype === 'ppt') {
              // 返回 Promise 以实现异步拦截
              return new Promise(async (resolve) => {
                try {
                  const is_zhu = await that.isMoney(100); // 等待异步验证
                  if (!is_zhu) {
                    resolve(false);
                    return;
                  }

                  const is_ty = await that.isTbi(); // 顺序执行第二个验证
                  if (!is_ty) {
                    resolve(false);
                    return;
                  }

                  that.docmeeUI.sendMessage({
                    type: 'success',
                    content: '继续生成PPT'
                  });
                  resolve(true); // 验证通过
                  //调用扣除T币的方法
                  that.pptUsePost(200)
                } catch (error) {
                  console.error('验证失败:', error);
                  resolve(false);
                }
              });
            }
          } else if (message.type === 'beforeCreateCustomTemplate') {
            const {file, totalPptCount} = message.data
            if (totalPptCount < 2) {
              return ElMessageBox.alert(
                  '用户生成积分不足，不允许制作自定义完整模版',
                  '提示',
                  { confirmButtonText: '知道了' }
              );
            } else {
              return (async () => {
                try {
                  if (!(await that.isMoney(200))) return false;
                  if (!(await that.isTbiMb())) return false;
                  const success = await that.pptUsePost(200);
                  if (!success) return false;
                  return true;
                } catch (error) {
                  console.error('权限验证失败:', error);
                  return false;
                }
              })();
            }

          } else if (message.type == 'pageChange') {
            that.pageChange(message.data.page)
          } else if (message.type === 'beforeDownload') {
            // 自定义下载PPT的文件名称
            const {id, subject} = message.data
            return `PPT_${subject}.pptx`
          } else if (message.type == 'error') {
            if (message.data.code == 88) {
              // 创建token传了limit参数可以限制使用次数
              return ElMessageBox.confirm(
                  '您的次数已用完',
                  '提示',
                  {
                    showClose: false,
                    showCancelButton:false,
                    confirmButtonText: '知道了',
                    cancelButtonText: '关闭'
                  });
            } else {
              return ElMessageBox.confirm(
                  '发生错误：' + message.data.message,
                  '提示',
                  {
                    showClose: false,
                    showCancelButton:false,
                    confirmButtonText: '知道了',
                    cancelButtonText: '关闭'
                  });
            }
          }
        }
      })
      this.docmeeUI = docmeeUI
    },
    toPage(page) {
      this.docmeeUI.navigate({ page })
      this.pageChange(page)
    },
    pageChange(page) {
      let element = document.getElementById('page_' + page)
      if (element) {
        element.parentNode.childNodes.forEach(c => c.classList && c.classList.remove('selected'))
        element.classList.add('selected')
      }
    }
  },
  mounted() {

    const userStore = useUserStore()
    this.uid = userStore.userInfo.id
    if(this.uid > 0){
      this.createApiToken(); // 创建token
    }else{
      userStore.setLoginPopupType(LoginPopupTypeEnum.LOGIN)
      userStore.toggleShowLogin(true)
    }
  }
};
</script>

<style scoped>
.body {
  margin: 0;
  width: 90vw;
  height: 100vh;
}

.page_navigate {
  padding: 5px;
  height: 45px;
  width: calc(100% - 50px);
  display: flex;
  justify-content: center;
  align-items: center;
}

.page_navigate > div {
  padding: 8px 16px;
  margin-right: 8px;
  cursor: pointer;
  user-select: none;
  border: 2px solid #f0f0f0;
  border-radius: 6px;
}

.page_navigate .selected {
  background: #f57bb0;
}

#container {
  width: calc(100% - 50px);
  height: calc(100% - 100px);
  margin: 0 auto;
  padding: 0;
  border-radius: 12px;
  box-shadow: 0 0 12px rgba(120, 120, 120, 0.3);
  overflow: hidden;
  background: linear-gradient(-157deg, #f57bb0, #867dea);
  color: white;
}
</style>
